<template>
<view @click.stop.prevent="noEvent">
	<view :class="['payList', { 'model-in': show }]">
		<view class="mask" @tap="close"></view>
		<view :class="['pay', { hide: !from }]">
			<form v-for="item in list" :key="item.id" @submit="toPay($event, item.id)" report-submit :class="item.class">
				<view class="item"><button plain formType="submit">{{ item.name }}</button></view>				
			</form>
		</view>
		<view :class="['password-input', { act: keyboard && !verify }]">
			<view v-for="(i, idx) in 6" :key="idx"><view :class="{ act: idx < password.length }"></view></view>
		</view>
		<view :class="['password-input code', { act: keyboard && verify }]">
			<view class="title solid-bottom">发送验证码</view>
			<view class="tip padding-top-sm padding-bottom-sm text-sm text-lgrey text-center solid-bottom">验证码已发送到{{ phone }}</view>
			<view class="verify">
				<view class="code">
					<view v-for="(i, k) in 6" :class="{act: v_code[k] !== undefined }" :key="i">
						{{ v_code[k] ? v_code[k] : '' }}
					</view>
				</view>
			</view>
		</view>					
		<key-board :show="keyboard" @on-close="closeBoard" @on-key="reset" @on-del="del" :verify="verify"></key-board>
	</view>	
</view>
</template>

<script>
	import { payList, oPayList, personalPay, productVirtual, packagePay } from '@/common/api/users'
	import KeyBoard from './keyboard'
	import { sendPhoneMsg } from '@/common/api'	
	import { mapGetters } from 'vuex'
	export default {
		props: {
			show: {
				type: Boolean,
				default: false
			},
			packageTag: {
				type: Number,
				default: 0
			},
			params: {
				type: Object,
				default: () => {}
			},
			pid: {
				type: String,
				default: ''
			},
			payWay: {
				type: Number,
				default: 0
			},		
			give: Function,
			divFun: { // 是否开启自定义支付函数
				type: Number,
				default: 1 // 1 不开启， 0 开启
			}
		},
		components: { KeyBoard },
		computed: {
			...mapGetters([
				'userInfo',
				'shop'
			]),
			phone () {
				if (this.userInfo.phone) {
					return this.userInfo.phone.substr(0, 3) + '****' + this.userInfo.phone.substr(7)
				}
				return ''
			},
			v_code () {
				return this.vcode.split('')
			},			
			payItem () {
				let obj = {}
				let o = { }
				if (this.pay_id !== '') {
					obj = this.list.filter(item => item.id === this.pay_id)[0]
					o = { pay_id: obj.id, paystyle: obj.name, type: 2 }
					}
				if (obj.id === 3) {
					return o
				}
				return Object.assign({}, o, this.wx_params) 
			}
		},
		data () {
			return {
				list: [],
				verify: '',
				keyboard: false,
				password: '',
				pay_id: '',
				from: 1,
				vcode: '',
				wx_params: {
					appid: this.$appid
				}
			}
		},
		created() {
			this.getList()
			this.$bus.on('on-keyboard', value => {
				this.keyboard = true
				this.from = value
			})
		},
		destroyed () {
			this.$bus.off('on-keyboard')
		},
		watch: {
			password (val, oldval) {
				if (val.length === 6) {
					this.password = ''
					if (val === this.userInfo.pay_pwd) {
						if (!this.shop.is_moneypay_sms) this.keyboard = false
						if (this.divFun) {
							if(this.from) {
								if (this.shop.type === 5) {
									if (this.shop.is_moneypay_sms) {
										this.sendSMS()
									} else {
										this.PayWay()
										setTimeout(() => { this.$emit('close-pay') }, 1000)
									}
								} else if (this.shop.type === 1) {
									this.$emit('on-line', this.pay_id)
									setTimeout(() => { this.$emit('close-pay') }, 1000)
								}
								} else {
								this.give()
							}							
						} else {
							this.$emit('myPay', this.payItem)
						}
					} else {
						uni.showToast({
							icon: 'none',
							title: '密码错误',
							mask: false,
							duration: 1500
						});
					}
				}
			},
			vcode (val, oldval) {
				if (val.length === 6) {
					if (val === this.verify) {
							this.PayWay()
							setTimeout(() => { this.$emit('close-pay') }, 1000)
					} else {
						uni.showModal({
							content: '验证码错误',
							showCancel: false
						})
						this.vcode = ''
					}					
				}
			}			
		},
		methods: {
			noEvent () {
				// 废弃
			},
			sendSMS () {
				uni.showLoading({ mask: true })
				sendPhoneMsg({ phone: this.userInfo.phone, action: 1 }).then(res => {
					uni.hideLoading()
					if (!res.code) {
						uni.showToast({
							title: '验证码发送成功',
							duration: 3000,
							success: () => {
								this.verify = res.mcode
							}
						})						
					} else {
						uni.uni.showModal({
							content: res.msg,
							showCancel: false
						})
					}
				})				
			},			
			reset (e) {
				if (this.password.length < 6 || (this.verify && this.vcode.length < 6)) {
					this.verify ? this.vcode += e : this.password += e
				}
			},
			del () {
				if (this.password > 0 || (this.verify && this.vcode.length > 0)) {
					this.verify ? this.vcode = this.vcode.substr(0, this.vcode.length - 1) : this.password = this.password.substr(0, this.password.length - 1)
				} 
			},
			close () {
				if (this.keyboard) {
					this.keyboard = false
					this.verify = this.vcode =''
					if (!this.from) this.$emit('close-pay')
				} else {
					this.$emit('close-pay')
				}
			},
			closeBoard () {
				this.password = ''
				this.keyboard = false
				if (!this.from) this.$emit('close-pay')
			},
			getList () {
				let params = {}
				if (this.shop.type === 5) {
					params = { pid: this.pid }
				}
				let getPayList = payList
				if (this.shop.type === 1 && this.divFun) getPayList = oPayList
				getPayList(params).then(res => {
					let result = {
						code: res.code,
						data: res.data
					}
					if (this.shop.type === 1 && this.divFun) {
						result = {
							code: 0,
							data: res
						}
					}
					if (!result.code) {
						const list = []
						for (let i in result.data) {
							list.push(result.data[i])
						}
						this.list = list.map(item => {
							item.class = ''
							if (item.name === '零钱支付') item.class = "charge"
							if (item.name === '支付宝支付') item.class = 'zfb'
							if (item.name === '微信支付') item.class="weixin"
							return item
						})
					}
				})
			},
			toPay (e, id) { // 支付方式
			    this.pay_id = id
				// #ifdef MP-WEIXIN
				this.wx_params.formId = e.detail.formId
				this.wx_params.openid = this.userInfo.openid
				// #endif
				let showKey = () => {
					if (!this.userInfo.pay_pwd) {
						uni.showModal({
							content: '您还没有设置支付密码',
							confirmText: '去设置',
							success: res => {
								if (res.confirm) {
									uni.navigateTo({ url: '/assets/setpwd' })
								}
							}
						});
					} else if (!this.phone) {
						uni.showModal({
							content: '您还没有绑定手机号码',
							confirmText: '去绑定',
							success: rst => {
								if (rst.confirm) {
									uni.navigateTo({
										url: '/usercenter/editdata'
									})
								}
							}
						})
					} else {
						this.keyboard = true
					}					
				}
				switch(id) {
					case 1:
					if (this.shop.type === 1) showKey()
					break;
					case 3:
					showKey()					
					break;
					default:
					if (this.shop.type === 5) {
						this.divFun ? this.PayWay() : this.$emit('myPay', this.payItem)
					} else if (this.shop.type === 1) {
						this.divFun ? this.$emit('on-line', this.pay_id) : this.$emit('myPay', this.payItem)
					}
				}
			},
			orderPay (pay) { //商城订单支付
			  return new Promise(resolve => {
				pay({ ...this.params, pay_id: this.pay_id, password: this.userInfo.pay_pwd, ...this.wx_params, openid: this.userInfo.openid }).then(res => {
					if (this.pay_id === 3) {
						let status = this.payWay ? !res.code : res.code === 400000
						if (status) {
							productVirtual({ ...this.params, pay_id: this.pay_id, ...this.wx_params })
							uni.showModal({
								content: res.data.data || res.data,
								showCancel: false,
								success: res => {
									if (res.confirm) {
										if (!this.payWay) {
											uni.redirectTo({
												url: '/pages/orders/list?act=1',
											})											
										} else {
											if (this.payWay === 6) {
												uni.redirectTo({
													url: '/pages/orders/list?act=1'
												})												
											} else {
												if (this.packageTag === 6) {
													uni.redirectTo({
														url: '/pages/orders/list?act=7'
													})
												} else {
													uni.redirectTo({
														url: '/usercenter/grade'
													})													
												}
											}
										}
									}
								}
							})
						} else {
							uni.showModal({
								content: res.msg || res.data,
								mask: true,
								showCancel: false
							});
						}
					} else if (this.pay_id === 4 || this.pay_id === 5) {
						 let provider = ''
						 this.pay_id === 4 ? provider = 'wxpay' : provider = 'alipay'
						 if (res.status || !res.code) {
							 // #ifndef MP-WEIXIN
							 uni.requestPayment({
								 provider: provider,
								 orderInfo: res.data,
								success: (res) => {
									uni.redirectTo({
										url: '/pages/orders/list?act=1',
									})
								},
								fail: err => {
									console.log(JSON.stringify(err))
								}
							 })							 
							 // #endif
							 // #ifdef MP-WEIXIN
							 uni.requestPayment({
								 provider,
								 ...res.data,
								 success: r => {
									uni.redirectTo({
										url: '/pages/orders/list?act=1',
									})
								 },
								 fail: er => {
									 console.log(er)
								 }
							 });
							 // #endif
						 } else {
							 uni.showToast({
								icon: 'none',
								title: res.msg || res.data.return_msg || '支付失败，请稍后重试',
								mask: true
							 })
						 }						 
					}
					resolve()
				})				  
			  })
			},
			async PayWay () {
				uni.showLoading({ title: '支付中', mask: true })
				let pay = personalPay
				if (this.payWay) pay = packagePay 
				await this.orderPay(pay)
				uni.hideLoading()
			}			
		}
	}
</script>

<style lang="less" scoped>
@import '../common/styles/variables.less';	
.payList {
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	z-index: 770;
	visibility: hidden;
	&.model-in {
		visibility: visible;
		.mask {
			opacity: 1;			
		}
		.pay {
			transform: translate3d(0, 0, 0);
		}
	}
	.mask {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background:rgba(0, 0, 0, 0.4);
		transition-duration: .4s;
		will-change: opacity;
		opacity: 0;		
		z-index: 666
	}
	.pay {
		position: fixed;
		bottom: 0;
		contain: layout;
		left: 0;
		background-color:white;
		width: 100%;
		transform: translate3d(0, 100%, 0);
		transition-duration: .2s;
		transition-delay: .1s;
		will-change: transform;
		z-index: 776;
		&.hide {
			transform: translate3d(0, 100%, 0);
		}
		form {
			.item {
				height: @height;
				display: flex;
				align-items: center;
				justify-content: center;
				button {
					width: 100%;
					border: 0 none;
					border-radius: 0;
					font-size: 14px;
					color:@gray;
					appearance: none;
				}				
			}
			&:not(:last-of-type) {
				.item {
					.border-bottom(15upx);
				}
			}
			&.zfb {
				button {
					color: #1296db; 
				}
			}
			&.charge { 
				button {
					color:@red
				}
			}
			&.weixin {
				button {
					color:#2cc537;
				}
			}
		}
	}
	.password-input {
		display: flex;
		border: 1px solid #ddd;
		background-color: #fff;
		border-radius: 3px;
		/* #ifndef H5 */
		transform: translate3d(0, -100%, 0);
		/* #endif */
		/* #ifdef H5 */
		transform: translate3d(0, calc(-100% - var(--window-top)), 0);
		/* #endif */
		border-radius: 20upx;
		overflow: hidden;
		box-shadow:0px 0px 8px #e4e4e4;
		position: fixed;
		top: 0;
		left: 10%;
		right: 10%;
		width: 80%;
		transition: transform .2s cubic-bezier(.09,1.1,.71,1.31);
		will-change: transform;
		contain: layout;
		z-index: 777;
		&.act { 
			/* #ifndef H5 */
			transform: translate3d(0, calc(100% + 80upx), 0);
			/* #endif */
			/* #ifdef H5 */
			transform: translate3d(0, calc(100% + 80upx + var(--window-top)), 0);
			/* #endif */
		}
		view {
			flex: .5;
			border-right: 1px solid #f3f3f3;
			position: relative;
			& > view {
				width: 100%;
				padding-top: 100%;
				&.act {
					&::after {
						display: flex;
						align-items: center;
						justify-content: center;
						box-sizing: border-box;
						content: '\2022';
						position: absolute;
						width: 100%;
						height: 100%;
						top: 0;
						left: 0;
						font-size: 52upx;
					}
				}
			}
			&:nth-child(6) {
				border: none;
			}
		}
		&.code {
			border-radius: 10upx;
			flex-direction: column;
			flex-flow: column;
			&.act { 
				/* #ifndef H5 */
				transform: translate3d(0, calc(100% + 80upx), 0);
				/* #endif */
				/* #ifdef H5 */
				transform: translate3d(0, calc(70% + var(--window-top)), 0);
				/* #endif */
			}
			.title {
				display: flex;
				align-items: center;
				justify-content: center;				
				height: 80upx;
				flex: 1;
			}
			.verify {
				height: 80upx;
				.code {
					margin: 0 auto;
					display: flex;
					height: 100%;
					padding: 0;
					width: 80%;
					border: 0 none;
					view {
						display: flex;
						align-items: center;
						justify-content: center;
						font-size: 36upx;
						height: 100%;
						flex: 1;
						padding: 0;
						position: relative;
						border: 0 none;
						margin: 0 10upx;
						&.act {
							&::after {
								display: none;
							}
						}
						&::after {
							position: absolute;
							top: 50%;
							width: 100%;
							border-top:1px solid #bfbbbb;
							content: '';
						}
					}
				}
			}
		}		
	}	
}
</style>
